#include "BlockQueue.hpp"
#include "Task.hpp"


void* Consumer(void* args)
{
    BlockQueue<Task>* bq = static_cast<BlockQueue<Task>*>(args);

    while(true)
    {
        // int data = bq->pop();
        // 消费
        Task t = bq->pop();

        // 处理数据
        t();
        cout << "处理任务: " << t.GetTask() << " 处理结果: " << t.GetResult() 
            << " thread id: " << pthread_self() << endl;
    }
}

void* Productor(void* args)
{
    int len = opers.size();
    BlockQueue<Task>* bq = static_cast<BlockQueue<Task>*>(args);

    // int data = 0;
    while(true)
    {
        // data++;
        // bq->push(data);
        // 获取数据
        int data1 = rand() % 10 + 1;
        int data2 = rand() % 10;
        char oper = opers[rand() % len];
        Task t(data1, data2, oper);
        usleep(10);

        // 生产
        bq->push(t);
        cout << "生产一个任务: " << t.GetTask() << " thread id: " << pthread_self() << endl;
        sleep(1);
    }
}

int main()
{
    srand((unsigned int)time(nullptr));

    BlockQueue<Task>* bq = new BlockQueue<Task>();
    pthread_t c[3], p[5];

    for (int i = 0; i < 3; i++)
    {
        pthread_create(c + i, nullptr, Consumer, bq);
    }
    for (int i = 0; i < 5; i++)
    {
        pthread_create(p + i, nullptr, Productor, bq);
    }

    for (int i = 0; i < 3; i++)
    {
        pthread_join(c[i], nullptr);
    }
    for (int i = 0; i < 5; i++)
    {
        pthread_join(p[i], nullptr);
    }

    delete bq;
    return 0;
}